package warningnotices

import (
	"context"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	httpstransport "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
)

func MakeWarningNoticeHandler(warningNoticeService WarningNoticeService) http.Handler {
	warningNoticeEndpoint := makeWarningNoticeEndpoint(warningNoticeService)
	warningNoticeHandler := httpstransport.NewServer(warningNoticeEndpoint,
		decodeWarningNoticeRequest,
		encodeWarningNoticeResponse)
	r := mux.NewRouter()
	r.Handle("/api/v1/warning_notice", warningNoticeHandler).Methods("GET")
	return r
}

//解析预警请求
func decodeWarningNoticeRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	logger := NewKitLogger()
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		logger.Log("error", err)
		return nil, err
	}
	var info WarningNotice
	err = json.Unmarshal(body, &info)
	if err != nil {
		logger.Log("error", err)
		return nil, err
	}

	// 判断请求是否符合条件
	if info.UserId == nil {
		logger.Log("error", "userId 不存在")
		return nil, errors.New("userId 不存在")
	}
	if len(*info.UserId) == 0 {
		logger.Log("error", "userId 为空")
		return nil, errors.New("userId 为空")
	}

	return warningNoticeRequest{
		Body: info,
	}, nil
}

func encodeWarningNoticeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	w.Header().Set("Content-type", "applicatioon/json; charset=utf-8")
	return json.NewEncoder(w).Encode(response)
}
